import tkinter as tk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk


class VideoPlayer:
    def __init__(self, root):
        self.root = root
        self.root.title("Video Player")

        # 主框架，用于容纳视频显示区域和控制区域
        self.main_frame = tk.Frame(self.root)
        self.main_frame.pack(padx=10, pady=10)

        # 视频显示标签，用于展示视频帧
        self.video_label = tk.Label(self.main_frame)
        self.video_label.pack()

        # 控制界面框架，放置在主框架下方
        self.control_frame = tk.Frame(self.main_frame)
        self.control_frame.pack(pady=(0, 10))

        # 打开文件按钮
        self.open_button = tk.Button(self.control_frame, text="Open Video", command=self.open_file)
        self.open_button.pack(side=tk.LEFT, padx=5)

        # 播放/暂停按钮
        self.play_pause_button = tk.Button(self.control_frame, text="Play", command=self.toggle_play)
        self.play_pause_button.pack(side=tk.LEFT, padx=5)

        self.cap = None
        self.is_playing = False
        self.update_video_frame()

    def open_file(self):
        file_path = filedialog.askopenfilename(title="Select Video", filetypes=(("Video files", "*.mp4;*.avi"),))
        if file_path:
            if self.cap:
                self.cap.release()
            self.cap = cv2.VideoCapture(file_path)
            self.is_playing = True

    def update_video_frame(self):
        if self.cap and self.is_playing:
            ret, frame = self.cap.read()
            if ret:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame)
                img = ImageTk.PhotoImage(image=img)
                self.video_label.imgtk = img
                self.video_label.configure(image=img)
            else:
                self.is_playing = False  # 视频播放完毕，停止播放
        self.root.after(15, self.update_video_frame)

    def toggle_play(self):
        if self.cap:
            self.is_playing = not self.is_playing
            if self.is_playing:
                self.play_pause_button.config(text="Pause")
            else:
                self.play_pause_button.config(text="Play")


if __name__ == "__main__":
    root = tk.Tk()
    app = VideoPlayer(root)
    root.mainloop()